﻿using AutoMapper;
using QYmall.Core.API.Filters;
using QYmall.Core.Common.Emum;
using QYmall.Core.Common.Extensions;
using QYmall.Core.Common.Helper;
using QYmall.Core.IServices;
using QYmall.Core.Model.Models;
using QYmall.Core.Model.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.JsonPatch;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace QYmall.Core.API.Controllers
{
    /// <summary>
    /// 优惠券历史记录
    /// </summary>
    [Route("admin/shop/coupon/history")]
    [ApiController]
    public class ShopCouponHistoryController : ControllerBase
    {
        private readonly IShopCouponHistoryService _shopCouponHistoryService;
        private readonly IUserService _userService;
        private readonly IMapper _mapper;
        
        /// <summary>
        /// 依赖注入
        /// </summary>
        public ShopCouponHistoryController(IShopCouponHistoryService shopCouponHistoryService, IUserService userService, IMapper mapper)
        {
            _shopCouponHistoryService = shopCouponHistoryService;
            _userService = userService;
            _mapper = mapper;
        }

        #region 管理员调用接口==========================
        /// <summary>
        /// 根据ID获取数据
        /// 示例：/admin/shop/coupon/history/1
        /// </summary>
        [HttpGet("{id}")]
        [Authorize]
        [AuthorizeFilter("ShopCoupon", ActionType.View)]
        public async Task<IActionResult> GetById([FromRoute] long id, [FromQuery] BaseParameter param)
        {
            //检测参数是否合法
            if (!param.Fields.IsPropertyExists<ShopCouponHistoryDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }
            //查询数据库获取实体
            var model = await _shopCouponHistoryService.QueryAsync<ShopCouponHistory>(x => x.Id == id, WriteRoRead.Write);
            if (model == null)
            {
                return BadRequest(ResponseMessage.Error($"数据{id}不存在或已删除"));
            }
            //使用AutoMapper转换成ViewModel，根据字段进行塑形
            var result = _mapper.Map<ShopCouponHistoryDto>(model).ShapeData(param.Fields);
            return Ok(result);
        }

        /// <summary>
        /// 获取指定数量列表
        /// 示例：/admin/shop/coupon/history/view/10
        /// </summary>
        [HttpGet("view/{top}")]
        [Authorize]
        [AuthorizeFilter("ShopCoupon", ActionType.View)]
        public async Task<IActionResult> GetList([FromRoute] int top, [FromQuery] OrderParameter searchParam)
        {
            //检测参数是否合法
            if (searchParam.OrderBy != null
                && !searchParam.OrderBy.Replace("-", "").IsPropertyExists<ShopCouponHistoryDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的排序参数"));
            }
            if (!searchParam.Fields.IsPropertyExists<ShopCouponHistoryDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }

            //获取数据库列表
            var resultFrom = await _shopCouponHistoryService.QueryListAsync(top,
                x => (!searchParam.OrderNo.IsNotNullOrEmpty() || (x.OrderNo != null && x.OrderNo.Equals(searchParam.OrderNo)))
                && (!searchParam.Keyword.IsNotNullOrEmpty() || (x.ShopCoupon != null && x.ShopCoupon.Title != null && x.ShopCoupon.Title.Contains(searchParam.Keyword))),
                searchParam.OrderBy ?? "-AddTime,-Id");

            //映射成DTO，根据字段进行塑形
            var resultDto = _mapper.Map<IEnumerable<ShopCouponHistoryDto>>(resultFrom).ShapeData(searchParam.Fields);
            //返回成功200
            return Ok(resultDto);
        }

        /// <summary>
        /// 获取分页列表
        /// 示例：/admin/shop/coupon/history?pageSize=10&pageIndex=1
        /// </summary>
        [HttpGet]
        [Authorize]
        [AuthorizeFilter("ShopCoupon", ActionType.View)]
        public async Task<IActionResult> GetList([FromQuery] OrderParameter searchParam, [FromQuery] PageParamater pageParam)
        {
            //检测参数是否合法
            if (searchParam.OrderBy != null
                && !searchParam.OrderBy.Replace("-", "").IsPropertyExists<ShopCouponHistoryDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的排序参数"));
            }
            if (!searchParam.Fields.IsPropertyExists<ShopCouponHistoryDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }

            //获取数据列表，如果ID大于0则查询该用户下所有的列表
            var list = await _shopCouponHistoryService.QueryPageAsync(
                pageParam.PageSize,
                pageParam.PageIndex,
                 x => (!searchParam.OrderNo.IsNotNullOrEmpty() || (x.OrderNo != null && x.OrderNo.Equals(searchParam.OrderNo)))
                && (!searchParam.Keyword.IsNotNullOrEmpty() || (x.ShopCoupon != null && x.ShopCoupon.Title != null && x.ShopCoupon.Title.Contains(searchParam.Keyword))),
                searchParam.OrderBy ?? "-AddTime,-Id");

            //x-pagination
            var paginationMetadata = new
            {
                totalCount = list.TotalCount,
                pageSize = list.PageSize,
                pageIndex = list.PageIndex,
                totalPages = list.TotalPages
            };
            Response.Headers.Add("x-pagination", SerializeHelper.SerializeObject(paginationMetadata));

            //映射成DTO，根据字段进行塑形
            var resultDto = _mapper.Map<IEnumerable<ShopCouponHistoryDto>>(list).ShapeData(searchParam.Fields);
            return Ok(resultDto);
        }

        /// <summary>
        /// 添加一条记录
        /// 示例：/admin/shop/coupon/history
        /// </summary>
        [HttpPost]
        [Authorize]
        [AuthorizeFilter("ShopCoupon", ActionType.Add)]
        public async Task<IActionResult> Add([FromBody] ShopCouponHistoryEditDto modelDto)
        {
            //检查会员是否正确
            if(!await _shopCouponHistoryService.ExistsAsync<Members>(x => x.UserId == modelDto.UserId))
            {
                return BadRequest(ResponseMessage.Error("会员账户不存在或已删除"));
            }
            //映射成实体
            var model = _mapper.Map<ShopCouponHistory>(modelDto);
            model.AddTime = DateTime.Now;

            //写入数据库
            var mapModel = await _shopCouponHistoryService.AddAsync(model);
            //映射成DTO再返回，否则出错
            var result = _mapper.Map<ShopCouponHistoryDto>(mapModel);
            return Ok(result);
        }

        /// <summary>
        /// 修改一条记录
        /// 示例：/admin/shop/coupon/history/1
        /// </summary>
        [HttpPut("{id}")]
        [Authorize]
        [AuthorizeFilter("ShopCoupon", ActionType.Edit)]
        public async Task<IActionResult> Update([FromRoute] long id, [FromBody] ShopCouponHistoryEditDto modelDto)
        {
            //检查会员是否正确
            if (!await _shopCouponHistoryService.ExistsAsync<Members>(x => x.UserId == modelDto.UserId))
            {
                return BadRequest(ResponseMessage.Error("会员账户不存在或已删除"));
            }
            //查找记录
            var model = await _shopCouponHistoryService.QueryAsync<ShopCouponHistory>(x => x.Id == id);
            if (model == null)
            {
                return BadRequest(ResponseMessage.Error($"数据{id}不存在或已删除"));
            }

            //更新操作AutoMapper替我们完成，只需要调用保存即可
            _mapper.Map(modelDto, model);
            var result = await _shopCouponHistoryService.SaveAsync();
            return NoContent();
        }

        /// <summary>
        /// 局部更新一条记录
        /// 示例：/admin/shop/coupon/history/1
        /// Body：[{"op":"replace","path":"/title","value":"new title"}]
        /// </summary>
        [HttpPatch("{id}")]
        [Authorize]
        [AuthorizeFilter("ShopCoupon", ActionType.Edit)]
        public async Task<IActionResult> Update([FromRoute] long id, [FromBody] JsonPatchDocument<ShopCouponHistoryEditDto> patchDocument)
        {
            var model = await _shopCouponHistoryService.QueryAsync<ShopCouponHistory>(x => x.Id == id);
            if (model == null)
            {
                return BadRequest(ResponseMessage.Error($"数据{id}不存在或已删除"));
            }

            var modelToPatch = _mapper.Map<ShopCouponHistoryEditDto>(model);
            patchDocument.ApplyTo(modelToPatch, ModelState);
            //验证数据是否合法
            if (!TryValidateModel(modelToPatch))
            {
                return ValidationProblem(ModelState);
            }
            //更新操作AutoMapper替我们完成，只需要调用保存即可
            _mapper.Map(modelToPatch, model);
            await _shopCouponHistoryService.SaveAsync();

            return NoContent();
        }

        /// <summary>
        /// 删除一条记录
        /// 示例：/admin/shop/coupon/history/1
        /// </summary>
        [HttpDelete("{id}")]
        [Authorize]
        [AuthorizeFilter("ShopCoupon", ActionType.Delete)]
        public async Task<IActionResult> Delete([FromRoute] long id)
        {
            if (!await _shopCouponHistoryService.ExistsAsync<ShopCouponHistory>(x => x.Id == id))
            {
                return BadRequest(ResponseMessage.Error($"数据{id}不存在或已删除"));
            }
            var result = await _shopCouponHistoryService.DeleteAsync<ShopCouponHistory>(x => x.Id == id);

            return NoContent();
        }

        /// <summary>
        /// 批量删除记录
        /// 示例：/admin/shop/coupon/history?ids=1,2,3
        /// </summary>
        [HttpDelete]
        [Authorize]
        [AuthorizeFilter("ShopCoupon", ActionType.Delete)]
        public async Task<IActionResult> DeleteByIds([FromQuery] string Ids)
        {
            if (Ids == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不可为空"));
            }
            //将ID列表转换成IEnumerable
            var arrIds = Ids.ToIEnumerable<long>();
            if (arrIds == null)
            {
                return BadRequest(ResponseMessage.Error("传输参数不符合规范"));
            }
            //执行批量删除操作
            await _shopCouponHistoryService.DeleteAsync<ShopCouponHistory>(x => arrIds.Contains(x.Id));

            return NoContent();
        }
        #endregion

        #region 商家调用接口============================
        /// <summary>
        /// 获取指定数量列表
        /// 示例：/merchant/shop/coupon/history/view/10
        /// </summary>
        [HttpGet("/merchant/shop/coupon/history/view/{top}")]
        [Authorize]
        public async Task<IActionResult> MerchantGetList([FromRoute] int top, [FromQuery] OrderParameter searchParam)
        {
            //检测参数是否合法
            if (searchParam.OrderBy != null
                && !searchParam.OrderBy.Replace("-", "").IsPropertyExists<ShopCouponHistoryDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的排序参数"));
            }
            if (!searchParam.Fields.IsPropertyExists<ShopCouponHistoryDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            //获取商家信息
            var merchantModel = await _shopCouponHistoryService.QueryAsync<Merchants>(x => x.UserId == userId);
            if (merchantModel == null)
            {
                return Unauthorized(ResponseMessage.Error("尚未开通商户功能，请检查重试"));
            }
            if (merchantModel.IsLock != 0)
            {
                return Unauthorized(ResponseMessage.Error("商户尚未开通，请等待审核通过"));
            }

            //获取数据库列表
            var resultFrom = await _shopCouponHistoryService.QueryListAsync(top,
                x => x.ShopCoupon != null
                && x.ShopCoupon.MerchantId == merchantModel.Id
                && (!searchParam.OrderNo.IsNotNullOrEmpty() || (x.OrderNo != null && x.OrderNo.Equals(searchParam.OrderNo)))
                && (!searchParam.Keyword.IsNotNullOrEmpty() || (x.ShopCoupon.Title != null && x.ShopCoupon.Title.Contains(searchParam.Keyword))),
                searchParam.OrderBy ?? "-AddTime,-Id");

            //映射成DTO，根据字段进行塑形
            var resultDto = _mapper.Map<IEnumerable<ShopCouponHistoryDto>>(resultFrom).ShapeData(searchParam.Fields);
            //返回成功200
            return Ok(resultDto);
        }
        #endregion

        #region 普通账户调用接口========================
        /// <summary>
        /// 获取会员优惠券分页列表
        /// 示例：/account/coupon/history?pageSize=10&pageIndex=1
        /// </summary>
        [HttpGet("/account/coupon/history")]
        [Authorize]
        public async Task<IActionResult> AccountGetList([FromQuery] BaseParameter searchParam, [FromQuery] PageParamater pageParam)
        {
            //检测参数是否合法
            if (searchParam.OrderBy != null
                && !searchParam.OrderBy.Replace("-", "").IsPropertyExists<ShopCouponHistoryDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的排序参数"));
            }
            if (!searchParam.Fields.IsPropertyExists<ShopCouponHistoryDto>())
            {
                return BadRequest(ResponseMessage.Error("请输入正确的属性参数"));
            }
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            if (userId == 0)
            {
                return NotFound(ResponseMessage.Error("用户尚未登录"));
            }

            //获取数据列表，如果ID大于0则查询该用户下所有的列表
            var list = await _shopCouponHistoryService.QueryPageAsync(
                pageParam.PageSize,
                pageParam.PageIndex,
                x => x.UserId == userId
                && x.ShopCoupon != null
                && x.ShopCoupon.IsDelete == 0
                && (searchParam.MerchantId == 0 || searchParam.MerchantId == x.ShopCoupon.MerchantId)
                && (!searchParam.Keyword.IsNotNullOrEmpty() || (x.OrderNo != null && x.OrderNo.Contains(searchParam.Keyword))),
                searchParam.OrderBy ?? "-AddTime,-Id");

            //x-pagination
            var paginationMetadata = new
            {
                totalCount = list.TotalCount,
                pageSize = list.PageSize,
                pageIndex = list.PageIndex,
                totalPages = list.TotalPages
            };
            Response.Headers.Add("x-pagination", SerializeHelper.SerializeObject(paginationMetadata));

            //映射成DTO，根据字段进行塑形
            var resultDto = _mapper.Map<IEnumerable<ShopCouponHistoryDto>>(list).ShapeData(searchParam.Fields);
            return Ok(resultDto);
        }

        /// <summary>
        /// 添加一条记录
        /// 示例：/account/shop/coupon/add
        /// </summary>
        [HttpPost("/account/shop/coupon/add")]
        [Authorize]
        public async Task<IActionResult> AccountAdd([FromBody] ShopCouponHistoryEditDto modelDto)
        {
            var mapModel = await _shopCouponHistoryService.AddAsync(modelDto);
            //映射成DTO再返回，否则出错
            var result = _mapper.Map<ShopCouponHistoryDto>(mapModel);
            return Ok(result);
        }

        /// <summary>
        /// 获取会员可用优惠券总数量
        /// 示例：/account/shop/coupon/count
        /// </summary>
        [HttpGet("/account/shop/coupon/count")]
        [Authorize]
        public async Task<IActionResult> AccountGetCount([FromQuery] GoodsParameter searchParam)
        {
            //获取登录用户ID
            int userId = await _userService.GetUserIdAsync();
            if (userId == 0)
            {
                return BadRequest(ResponseMessage.Error("用户尚未登录"));
            }
            var result = await _shopCouponHistoryService.QueryCountAsync(
                x => x.UserId == userId
                && x.Status == 0
                && x.IsUse == 0
                && x.ShopCoupon != null
                && x.ShopCoupon.IsDelete == 0
                && DateTime.Compare(x.ShopCoupon.StartTime, DateTime.Now) <= 0
                && DateTime.Compare(x.ShopCoupon.EndTime, DateTime.Now) >= 0);
            //返回成功200
            return Ok(result);
        }
        #endregion
    }
}
